package com.zeedev.flyingsaucer.beers.activities.home.impl;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.zeedev.flyingsaucer.global.UfoClubApp;
import mobi.zeedev.flyingsaucer.common.CredentialsModule.impl.HomeInfo;
import mobi.zeedev.flyingsaucer.common.CredentialsModule.interfaces.IPreferenceCredentials;

import java.beans.PropertyChangeSupport;

/**
 * User: James Johnson
 * Date: Oct 29, 2010
 * Time: 7:23:28 PM
 */
@Singleton
public class HomeModel {

    Integer refreshingCount;

    private HomeInfo homeInfo;

    PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    public enum Properties {
        REFRESHING,
        HOME_INFO,
        CREDENTIALS
    }

    @Inject
    public HomeModel(HomeInfo homeInfo) {
        refreshingCount = 0;
        this.homeInfo = homeInfo;
    }

    @Inject
    @Named("autoIPreferenceCredentials")
    Provider<IPreferenceCredentials> credentials;

    @Inject
    UfoClubApp app;

    public HomeInfo getHomeInfo() {
        return homeInfo;
    }

    public void setHomeInfo(HomeInfo homeInfo) {
        HomeInfo oldValue = this.homeInfo;
        this.homeInfo = homeInfo;

        homeInfo.bindToPreferences(app);
        credentials.get().getCredentials().setUserName(homeInfo.get(HomeInfo.E_MAIL));
        credentials.get().bindToPreferences();

        pcs.firePropertyChange(Properties.HOME_INFO.name(), oldValue, homeInfo);
    }

    public Boolean isRefreshing() {
        return refreshingCount > 0;
    }

    public void setRefreshing(Boolean refreshing) {
        Boolean oldValue = isRefreshing();
        if (refreshing) {
            refreshingCount++;
        } else {
            refreshingCount--;
        }
        if (refreshingCount < 0) {
            refreshingCount = 0;
        }
        if (refreshingCount > 2) {
            refreshingCount = 0;
        }
        Boolean newValue = isRefreshing();

        pcs.firePropertyChange(Properties.REFRESHING.name(), oldValue, newValue);
    }


}
